//
//  StartViewController.m
//  Elimination
//
//  Created by A-01 on 2020/7/1.
//  Copyright © 2020 A-01. All rights reserved.
//

#import "StartViewController.h"
#import "UIView+ZYDraggable.h"
#import "ScoreViewController.h"
#import "AVFoundation/AVFoundation.h"
#import "AudioToolBox/AudioToolBox.h"

@interface StartViewController ()<CAAnimationDelegate,AVAudioPlayerDelegate>

@property (nonatomic, weak)UILabel * titleLabel;
@property (nonatomic, strong)UIButton * pauseButton;
@property (nonatomic, strong)UIButton * voiceButton;
@property (nonatomic, strong)UIButton * replayButton;
@property (nonatomic, weak)UIView * bottomView;
@property (nonatomic, strong)NSTimer * countDownTimer;
@property (nonatomic, strong)NSMutableArray * imgarray;
@property (nonatomic, strong)UIImageView * oneImageView;
@property (nonatomic, strong)UIImageView * twoImageView;
@property (nonatomic, strong)UIImageView * threeImageView;
@property (nonatomic, strong) AVAudioPlayer * audioPlayer;

@end

@implementation StartViewController

//倒计时总的秒数
static NSInteger  secondsCountDown = 100;
static NSInteger  count = 0;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.backImageView.image = [UIImage imageNamed:@"playBackView"];
    [self setupUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endMovePan:) name:@"endMovePan" object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    
    secondsCountDown = 100;
    count = 0;
    self.titleLabel.text = @"00";
    self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
    for (UIImageView * img in self.imgarray) {
        
        [img removeFromSuperview];
    }
    [self.imgarray removeAllObjects];
}


-(void)viewDidDisappear:(BOOL)animated{
    
    [self.countDownTimer invalidate];
}


- (void)setupUI{
    
    UILabel * titleLabel = [UILabel new];
    
    titleLabel.text = @"Score: 00";
    titleLabel.textColor = ZRWhiteColor;
    titleLabel.font = [UIFont fontWithName:@"FZSEJW--GB1-0" size:30];
    
    self.titleLabel = titleLabel;
    
    [self.view addSubview:self.titleLabel];
    
    self.pauseButton = [self setupButtonWithImg:@"pause"];
    [self.pauseButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateSelected];
    [self.view addSubview:self.pauseButton];
    self.voiceButton = [self setupButtonWithImg:@"sound"];
    [self.voiceButton setImage:[UIImage imageNamed:@"silent"] forState:UIControlStateSelected];
    [self.view addSubview:self.voiceButton];
    self.replayButton = [self setupButtonWithImg:@"restart"];
    [self.view addSubview:self.replayButton];
    
    UIView * bottomView = [UIView new];
    
    bottomView.backgroundColor = [UIColor colorWithHexString:@"5663B6"];
    bottomView.layer.cornerRadius = 27;
    bottomView.layer.masksToBounds = YES;
    
    self.bottomView = bottomView;
    
    [self.view addSubview:self.bottomView];
    
    self.oneImageView = [self setupImageView];
    [self.view addSubview:self.oneImageView];
    self.twoImageView = [self setupImageView];
    [self.view addSubview:self.twoImageView];
    self.threeImageView = [self setupImageView];
    [self.view addSubview:self.threeImageView];
    
    [self setupBottomImageView];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"backMusic" ofType:@"mp3"];
    NSURL *url = [[NSURL alloc] initFileURLWithPath:path];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    self.audioPlayer.volume = 1;
    self.audioPlayer.delegate = self;
    
    [self.audioPlayer play];
}

- (void)clickTopButton:(UIButton *)button{
    
    if (button == self.pauseButton) {
        
        button.selected = !button.selected;
        if (button.selected) {
            
            [self.countDownTimer invalidate];
            for (UIImageView * img in self.imgarray) {
                
                [img removeDraggable];
            }
        }else{
            
            self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
            for (UIImageView * img in self.imgarray) {
                
                [img makeDraggable];
            }
        }
    }else if (button == self.voiceButton) {
        
        button.selected = !button.selected;
        if (button.selected) {
            
            [self.audioPlayer pause];
        }else{
            
            [self.audioPlayer play];
        }
    }else{
        
        [self.countDownTimer invalidate];
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                  message:@"Are you sure you want to play again?"
                                                                           preferredStyle:UIAlertControllerStyleAlert];
                   
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"Sure" style:UIAlertActionStyleDefault
                                                                         handler:^(UIAlertAction * action) {
                                                                          
            secondsCountDown = 100;
            count = 0;
            self.titleLabel.text = @"00";
            self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
            for (UIImageView * img in self.imgarray) {
                
                [img removeFromSuperview];
            }
            [self.imgarray removeAllObjects];
                                                                         }];
        
        UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"Cancle" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
            
            self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
                                                                        }];
                   
        [alert addAction:defaultAction];
        [alert addAction:cancleAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}


//定时器的方法
- (void)countDownAction{
    
    secondsCountDown --;
    count ++;
    
    if (kScreenW > 40 * count + 20) {
        
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenW - (40 * count), kScreenH - 94, 40, 40)];
        NSString * img = [NSString stringWithFormat:@"%d",arc4random() % 24];
        imageView.image = [UIImage imageNamed:img];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
//        UIPanGestureRecognizer *panGP = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
        imageView.userInteractionEnabled = YES;
//        [imageView addGestureRecognizer:panGP];
        [self.view addSubview:imageView];

//        [UIView animateWithDuration:6 animations:^{
//
//            imageView.transform = CGAffineTransformMakeTranslation(kScreenW - (40 * count), 0);
//        } completion:^(BOOL finished) {
//
//            UIImage * grayImg = [self unableImage:imageView.image];
//            imageView.image = grayImg;
////            [imageView makeDraggable];
//        }];
//        //创建动画对象
//        CABasicAnimation *basicAni = [CABasicAnimation animation];
//        //设置动画属性
//        basicAni.keyPath = @"position";
//        //设置动画的起始位置。也就是动画从哪里到哪里
//        basicAni.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, kScreenH - 94)];
//        //动画结束后，layer所在的位置
//        basicAni.toValue = [NSValue valueWithCGPoint:CGPointMake(kScreenW - (40 * count), kScreenH - 94)];
//        //动画持续时间
//        basicAni.duration = 5;
//        //动画填充模式
//        basicAni.fillMode = kCAFillModeForwards;
//        //动画完成不删除
//        basicAni.removedOnCompletion = YES;
//        //xcode8.0之后需要遵守代理协议
//        basicAni.delegate = self;
//        //把动画添加到要作用的Layer上面
//        [imageView.layer addAnimation:basicAni forKey:nil];
        imageView.tag = count;
        [imageView makeDraggable];
        [self.imgarray addObject:imageView];
    }else{
        
        for (UIImageView * imageView in self.bottomView.subviews) {
            
            [imageView.layer removeAllAnimations];
        }
        
        ScoreViewController * scoreVC = [ScoreViewController new];
        
        scoreVC.score = self.titleLabel.text;
        
        [self.navigationController pushViewController:scoreVC animated:YES];
        
        DEF_SET_OBJECT(self.titleLabel.text, @"last");
        int oldScore = [DEF_GET_OBJECT(@"best") intValue];
        int newScore = [self.titleLabel.text intValue];
        
        if (newScore > oldScore) {
            
            NSString * best = [NSString stringWithFormat:@"%d",newScore];
            DEF_SET_OBJECT(best, @"best");
        }
    }
    //当倒计时到0时做需要的操作，button变成可选状态
    if(secondsCountDown==0){
        
        [_countDownTimer invalidate];
    }
}

////平移手势的回调方法
//- (void)panAction:(UIPanGestureRecognizer*)sender{
//    //得到当前手势所在视图
//    UIImageView * imageView = (UIImageView *)sender.view;
//    //得到我们在视图上移动的偏移量
//    CGPoint currentPoint = [sender translationInView:imageView.superview];
//    //通过2D仿射变换函数中与位移有关的函数实现视图位置变化
//    imageView.transform = CGAffineTransformTranslate(imageView.transform, currentPoint.x, currentPoint.y);
//    //复原 // 每次都是从00点开始
//    [sender setTranslation:CGPointZero inView:imageView.superview];
//
//    NSLog(@"=====%@",imageView);
//
//}
// 播放器代理 播放完成的时候再次播放
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [self.audioPlayer play];
}


- (void)endMovePan:(NSNotification *)noti{
    
    NSDictionary * dic = noti.userInfo;
    
    CGFloat x = [dic[@"x"] floatValue];
    CGFloat y = [dic[@"y"] floatValue];
    int index = [dic[@"tag"] intValue] - 1;
    UIImageView * imageView = self.imgarray[index];
    CGPoint panLocation = CGPointMake(x, y);
    
    CGFloat twoX = self.view.centerX - 45;
    CGRect oneRect = CGRectMake(twoX - 90 - 95, 89.6667, 90, 90);
    CGRect twoRect = CGRectMake(twoX, 89.6667, 90, 90);
    CGRect threeRect = CGRectMake(twoX + 90 + 95, 89.6667, 90, 90);
    
    if (CGRectContainsPoint(oneRect, panLocation) && self.oneImageView.image == imageView.image) {
        
        int score = [self.titleLabel.text intValue] + 10;
        self.titleLabel.text = [NSString stringWithFormat:@"%d",score];
        NSString * img = [NSString stringWithFormat:@"%d",arc4random() % 24];
        self.oneImageView.image = [UIImage imageNamed:img];
        [imageView removeFromSuperview];
        [self updateImageViewWithIndexpath:index];
        count --;
    }else if (CGRectContainsPoint(twoRect, panLocation) && self.twoImageView.image == imageView.image){
        
        int score = [self.titleLabel.text intValue] + 10;
        self.titleLabel.text = [NSString stringWithFormat:@"%d",score];
        NSString * img = [NSString stringWithFormat:@"%d",arc4random() % 24];
        self.twoImageView.image = [UIImage imageNamed:img];
        [imageView removeFromSuperview];
        [self updateImageViewWithIndexpath:index];
        count --;
    }else if (CGRectContainsPoint(threeRect, panLocation) && self.threeImageView.image == imageView.image){
        
        int score = [self.titleLabel.text intValue] + 10;
        self.titleLabel.text = [NSString stringWithFormat:@"%d",score];
        NSString * img = [NSString stringWithFormat:@"%d",arc4random() % 24];
        self.threeImageView.image = [UIImage imageNamed:img];
        [imageView removeFromSuperview];
        [self updateImageViewWithIndexpath:index];
        count --;
    }else{
        
        [imageView.zy_animator removeAllBehaviors];
        [imageView.zy_animator addBehavior:imageView.zy_snapBehavior];
    }
}


- (void)updateImageViewWithIndexpath:(NSInteger)index{
    
//    [self.imgarray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(UIImageView * obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        if (index < idx) {
//            
////            [UIView animateWithDuration:1 animations:^{
//               
//                obj.x +=40;
////            }];
////            obj.transform = CGAffineTransformMakeTranslation(kScreenW - (40 * (count - 1)), 0);
//        }
//    }];
    
    for (NSInteger i = index + 1; i < self.imgarray.count; i++) {
        
        UIImageView * imageView = self.imgarray[i];
        
        imageView.x +=40;
    }
    
    [self.imgarray removeObjectAtIndex:index];
}


- (void)viewDidLayoutSubviews{
    
    [super viewDidLayoutSubviews];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(30);
    }];
    
    [self.pauseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view).offset(20);
        make.trailing.mas_equalTo(self.view).offset(-25);
        make.height.width.mas_equalTo(24);
    }];
    
    [self.voiceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.pauseButton.mas_leading).offset(-16);
        make.centerY.height.width.mas_equalTo(self.pauseButton);
    }];
    
    [self.replayButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.voiceButton.mas_leading).offset(-16);
        make.centerY.height.width.mas_equalTo(self.voiceButton);
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(self.view);
        make.height.mas_equalTo(54);
    }];
    
    [self.twoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(25);
        make.centerX.mas_equalTo(self.view);
        make.height.width.mas_equalTo(90);
    }];
    
    [self.oneImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.twoImageView.mas_leading).offset(-95);
        make.centerY.height.width.mas_equalTo(self.twoImageView);
    }];
    
    [self.threeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.twoImageView.mas_trailing).offset(95);
        make.centerY.height.width.mas_equalTo(self.twoImageView);
    }];
}


-(void)setupBottomImageView
{

    float Start_X = 53.0f;   // 第一个按钮的X坐标
    float Start_Y = 7;    // 第一个按钮的Y坐标
    float Height_Space = (kScreenW - 426) / 7;     // 竖间距
    float Button_Height = 40.0f;    // 高
    for (int i = 0 ; i < 8; i++) {
        // 圆角按钮
        UIImageView *imageView = [UIImageView new];
        imageView.frame = CGRectMake(i * (Button_Height + Height_Space)+Start_X, Start_Y, Button_Height, Button_Height);
        imageView.image = [UIImage imageNamed:@"chi"];
        [self.bottomView addSubview:imageView];
        
        CABasicAnimation *animation =  [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        //默认是顺时针效果，若将fromValue和toValue的值互换，则为逆时针效果
        animation.fromValue = [NSNumber numberWithFloat:0.f];
        animation.toValue =  [NSNumber numberWithFloat: M_PI *2];
        animation.duration  = 3;
        animation.autoreverses = NO;
        animation.fillMode =kCAFillModeForwards;
        animation.repeatCount = MAXFLOAT; //如果这里想设置成一直自旋转，可以设置为MAXFLOAT，否则设置具体的数值则代表执行多少次
        [imageView.layer addAnimation:animation forKey:nil];
    }
}



- (UIButton *)setupButtonWithImg:(NSString *)img{
    
    UIButton * button = [UIButton new];
    
    [button setImage:[UIImage imageNamed:img] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(clickTopButton:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}


- (UIImageView *)setupImageView{
    
    UIImageView * imageView = [UIImageView new];
    
    NSString * img = [NSString stringWithFormat:@"%d",arc4random() % 24];
    imageView.image = [UIImage imageNamed:img];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    
    return imageView;
}


-(UIImage *)unableImage:(UIImage*)originImage{
 
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *superImage = [CIImage imageWithCGImage:originImage.CGImage];
    CIFilter *lighten = [CIFilter filterWithName:@"CIColorControls"];
    [lighten setValue:superImage forKey:kCIInputImageKey];
//    // 修改亮度   -1---1   数越大越亮
    [lighten setValue:@(0) forKey:@"inputBrightness"];
    
    // 修改饱和度  0---2
    [lighten setValue:@(0) forKey:@"inputSaturation"];
    
//    // 修改对比度  0---4
    [lighten setValue:@(0.5) forKey:@"inputContrast"];
    CIImage *result = [lighten valueForKey:kCIOutputImageKey];
    CGImageRef cgImage = [context createCGImage:result fromRect:[superImage extent]];
    // 得到修改后的图片
    UIImage *newImage =  [UIImage imageWithCGImage:cgImage];
    // 释放对象
    CGImageRelease(cgImage);
    return newImage;
}


- (NSMutableArray *)imgarray{
    
    if (!_imgarray) {
        
        _imgarray = [[NSMutableArray alloc] init];
    }
    
    return _imgarray;
}


-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
